<template>
    <div>
        <div class="title_class">
            <span class="title">{{title}}</span>
        </div>
        <Card style="width:100%;margin-bottom:15px;">
            <div>
                <Row>
                    <Col span="8">
                        <Form :label-width="80">
                           <FormItem label="选择编组" style="margin-bottom:0px;">
                                <Select v-model="activeitem">
                                    <Option v-for="(item,key) in itemlist" :key="key" :value = "item.id">{{item.name}}</Option>
                                </Select>
                           </FormItem>
                        </Form>
                    </Col>
                    <Col span="8">
                        <Form :label-width="80">
                            <FormItem label="选择日期" style="margin-bottom:0px;">
                                <DatePicker type="date" v-model = "default_month" style="width:100%;" @on-change="monthchange"></DatePicker>
                            </FormItem>
                        </Form>
                    </Col>
                    <Col span="8" style="padding-left:30px;">
                        <Button type="primary" @click="handleSearch">查询</Button>
                    </Col>
                </Row>
                
            </div>
        </Card>
        <Tabs v-model="tabactive" @on-click = "handleToggle">
            <TabPane :label="item.name" :name="item.name" v-for="(item,key) in tabTitle" :key="item.id">
                <Table :columns="columns" :data="data" style="margin-bottom:15px;"></Table>
                
                <div style="display:flex;justify-content:left;">
                    <div :id="'chart'+item.id" class="chart">

                    </div>
                </div>
            </TabPane>
        </Tabs>
    </div>
</template>
<script>
import util from '../../util/util'
export default {
    data(){
        return {
            title:'运行状态',
            issearch:false,
            currenpage:1,
            myChart:Object,
            typeindex:0,
            total:1,
            default_month:'',
            activeitem:'',
            tabactive:'',
            itemlist:[],
            tabTitle:[],
            Temperature_differencelist:[10,11,5],
            Temperature_differenceAxis:['周一','周二','周三'],
            myChartObj:'',
            columns: [
                {
                    title: '设备名称',
                    key: 'name'
                },
                {
                    title: '设备温度',
                    render:(h,params)=>{
                        return h('span',{},params.row.temp?params.row.temp+'℃':'-'+'℃')
                    }
                },
                {
                    title: '室内温度',
                    render:(h,params)=>{
                        return h('span',{},params.row.env_temp?params.row.env_temp+'℃':'-'+'℃')
                    }
                },{
                    title:"温差",
                    render:(h,params)=>{
                        return h('span',{},this.subtemp(params.row.temp,params.row.env_temp))
                    }
                },{
                    title:"状态",
                    key:"status",
                    render:(h, params) => {
                        let bck = "";
                        if(params.row.is_online==1){
                            bck = "#00a854";
                        }else{
                            bck = "red";
                        }
                        return h('div', [
                            h('div', {  
                                style: {  
                                    background:bck,
                                    borderRadius:"10px",
                                    width:'10px',
                                    height:'10px',
                                    display:'inline-block'
                                },  
                            }, ''),
                            h('strong', {  
                                style: {  
                                    marginLeft: '5px'  
                                },  
                            }, params.row.is_online==1?'在线':'离线'),    
                        ])
                    }
                }
            ],
            data: []
        }
    },
    created(){
        let date = new Date();
        let year = date.getFullYear();
        let month = date.getMonth()+1;
        let now = date.getDate();
        this.default_month = year+'-'+month+'-'+now;
        try{
            this.title = this.$store.state.DevclickItem.name;
        }catch(e){
            this.$router.go(-1)
        }
    },
    mounted(){
        this.$nextTick(()=>{
            this.get_Ts_Type_Group(this.$store.state.DevclickItem.name);
        })
    },
    methods:{
        monthchange:function(date){
            let vm = this;
            //vm.default_month = date;
        },
        getTableData:function(tyid,groupid,date,tsid,chartid,title){
            let vm = this;
            util.ajax({
                method: 'get',
                //url: '/api-record/device_month?ts_index='+tsid+'&group_index='+groupid+'&type_index='+tyid+'&date='+date
                url:'/api-record/device_day?ts_index='+tsid+'&group_index='+groupid+'&type_index='+tyid+'&date='+date
            })
            .then(function (response) {
                if(response.status==200){
                    vm.data = response.data.devices;
                    setTimeout(()=>{
                        vm.initChart('chart'+tyid,response.data.charts.x_series,response.data.charts.y_series,response.data.charts.env);
                    },100)
                }
            })
            .catch(function(err){
                console.log(err.response)
                vm.$Message.error('网络错误');
            })
        },
        get_Ts_Type_Group:function(tsname){
            let vm = this;
            util.ajax({
                method: 'get',
                url: '/util-api-sgdlist/?tsname='+tsname
            })
            .then(function (response) {
                if(response.status==200){
                    if(response.data.device_group.length==0){
                        vm.$Message.info('当前变电站无编组数据');
                        return false;
                    }
                    vm.itemlist = [];
                    vm.activeitem = response.data.device_group[0].id;
                    vm.tabactive = response.data.device_type[0].name;
                    for(let i = 0;i<response.data.device_group.length;i++){
                        vm.itemlist.push(response.data.device_group[i]);
                    }
                    vm.tabTitle = [];
                    for(let i = 0;i<response.data.device_type.length;i++){
                        vm.tabTitle.push(response.data.device_type[i]);
                    }
                    if(vm.tabTitle.length>0){
                        vm.typeindex = vm.tabTitle[0].id;
                    }else{
                        return false;
                    }

                    let date = new Date(vm.default_month);
                    let yy = date.getFullYear();
                    let mm = (date.getMonth()+1)>=10?(date.getMonth()+1):('0'+(date.getMonth()+1));
                    let dd = date.getDate();
                    let month = yy+'-'+mm+'-'+dd;
                    vm.getTableData(vm.typeindex,vm.activeitem,month,vm.$store.state.DevclickItem.id);
                }else{
                    vm.$Message.error('获取编组失败');
                }
            })
            .catch(function(err){
                vm.$Message.error('网络错误');
            })
        },
        handleSearch:function(){
            let date = new Date(this.default_month);
            let yy = date.getFullYear();
            let mm = (date.getMonth()+1)>=10?(date.getMonth()+1):('0'+(date.getMonth()+1));
            let dd = date.getDate();
            let month = yy+'-'+mm+'-'+dd;
            let title = month+'环境与设备温差趋势';
            this.getTableData(this.typeindex,this.activeitem,month,this.$store.state.DevclickItem.id,title);
        },
        handleReset:function(){

        },
        handleToggle:function(name){
            if(this.myChart){
                this.myChart.clear();
            }
            for(let i = 0;i < this.tabTitle.length;i++){
                if(name===this.tabTitle[i].name){
                    this.typeindex = this.tabTitle[i].id;
                    let date = new Date(this.default_month);
                    let yy = date.getFullYear();
                    let mm = (date.getMonth()+1)>=10?(date.getMonth()+1):('0'+(date.getMonth()+1));
                    let dd = date.getDate();
                    let month = yy+'-'+mm+'-'+dd;
                    let title = month + '环境与设备温差趋势';
                    this.getTableData(this.typeindex,this.activeitem,month,this.$store.state.DevclickItem.id,title);
                    break;
                }
            }
        },
        subtemp:function numSub(num1, num2) {
            let baseNum, baseNum1, baseNum2;
            let precision;// 精度
            try {
                baseNum1 = num1.toString().split(".")[1].length;
            } catch (e) {
                baseNum1 = 0;
            }
            try {
                baseNum2 = num2.toString().split(".")[1].length;
            } catch (e) {
                baseNum2 = 0;
            }
            baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
            precision = (baseNum1 >= baseNum2) ? baseNum1 : baseNum2;
            return ((num1 * baseNum - num2 * baseNum) / baseNum).toFixed(precision);
        },
        initChart:function(id,xAxis,data,env){
            //let echarts = require('echarts');
            let echarts = require('echarts/lib/echarts');
            // 引入柱状图
            require('echarts/lib/chart/line');
            require("echarts/lib/component/grid");
            require("echarts/lib/component/title");
            require("echarts/lib/component/markPoint");

            // 引入提示框和标题组件
            require('echarts/lib/component/tooltip');
            require('echarts/lib/component/toolbox');
            require("echarts/lib/component/dataZoom");
            this.myChart = echarts.init(document.getElementById(id));

            let serieslist = [];
            let legendd = [];
            for(let i=0;i<data.length;i++){
                if(data[i].data.length>0){
                    legendd.push(data[i].name);
                }
                
                let item = {
                    name:data[i].name,
                    type:'line',
                    data:data[i].data,
                    markPoint: {
                        data: [
                            {type: 'max', name: '最大值'},
                            {type: 'min', name: '最小值'}
                        ]
                    },
                    smooth:true,
                    markLine: {
                        data: [
                            {type: 'average', name: '平均值'}
                        ]
                    }
                };
                serieslist.push(item);
            }
            
            let envitem = {
                name:env.name,
                type:'line',
                data:env.data,
                markPoint: {
                    data: [
                        {type: 'max', name: '最大值'},
                        {type: 'min', name: '最小值'}
                    ]
                },
                smooth:true,
                markLine: {
                    data: [
                        {type: 'average', name: '平均值'}
                    ]
                }
            };
            serieslist.push(envitem);
            legendd.push(env.name);
            let option = {
                title: {
                    text: '设备与环境温差趋势',
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data:legendd,
                    top:30,
                },
                toolbox: {
                    feature: {
                        magicType: {
                            type: ['line', 'bar']
                        }
                    }
                },
                grid:{
                    left:'5%',
                    right:'5%'
                },
                xAxis:  {
                    type: 'category',
                    boundaryGap: false,
                    data: xAxis
                },
                yAxis: {
                    type: 'value',
                    axisLabel: {
                        formatter: '{value} °C'
                    }
                },
                dataZoom: [
                    {
                        show: true,
                        realtime: true,
                        start: 0,
                        end: 70
                    },
                    {
                        type: 'inside',
                        realtime: true,
                        start: 0,
                        end: 70
                    }
                ],
                series: serieslist
            };
            this.myChart.setOption(option);
            window.addEventListener('resize',() => {
                this.myChart.resize();
            })
        }
    }
}
</script>
<style scoped>
    .title{
        color: #0e90d2;
        font-size: 20px;
        font-weight: 700;
    }
    .title_class{
        position: relative;
        margin-bottom: 15px;
    }
    .chart{
        width: 100%;
        height: 350px;
    }
    .imgdiv{
        height: 350px;
    }
</style>
